//
//  KLComposeController.m
//  KL
//
//  Created by mac on 15/12/21.
//  Copyright © 2015年 zhouxubin. All rights reserved.
//
#define KLComposeKey @"7d8d915debefde5f28f9253e55f2d57f"
#define KLComposeAPI @"http://japi.juhe.cn/manmanmai/simple.from?"

#import "KLComposeController.h"
#import <SVProgressHUD.h>
#import "ZBNetWorkTool.h"
#import "KLCompose.h"
#import <MJExtension.h>
#import "KLComposeDetailController.h"

@interface KLComposeController ()
@property (weak, nonatomic) IBOutlet UIButton *checkButton;
@property (weak, nonatomic) IBOutlet UITextField *shopName;
/** 模型数据 */
@property (nonatomic, strong) NSArray *composeList;

@end

@implementation KLComposeController

#pragma mark - 查询按钮的点击事件
- (IBAction)composeButton {
    [self.view endEditing:YES];
    [SVProgressHUD showWithStatus:@"正在努力查询中..."];
    // 判断文本是否有字
    if (self.shopName.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入商品的名字!"];
        return;
    }
    
    // 发送请求 http://japi.juhe.cn/manmanmai/simple.from?key=YOURKEY&keyword=%E5%B0%8F%E7%B1%B3
    NSString *urlString = [NSString stringWithFormat:@"%@key=%@&keyword=%@", KLComposeAPI, KLComposeKey, [self converStringWith:self.shopName.text]];
    // 发送请求
    [[ZBNetWorkTool sharedNetWorkTool] GET:urlString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
        if (![responseObject[@"reason"] isEqualToString:@"success"] || [responseObject[@"result"] count] == 0) {
            [SVProgressHUD showErrorWithStatus:@"没有查询到结果!"];
            return;
        }
        
        // 正确查询
        self.composeList = [KLCompose mj_objectArrayWithKeyValuesArray:responseObject[@"result"] context:nil];
        // 跳转控制器
        KLComposeDetailController *detailVc = [[KLComposeDetailController alloc] init];
        detailVc.composeList = self.composeList;
        // 取消HUD
        [SVProgressHUD dismiss];
        
        [self.navigationController pushViewController:detailVc animated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 提示用户查询失败
        [SVProgressHUD showErrorWithStatus:@"网络繁忙,请稍后再试"];
    }];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    // 设置按钮的圆角
    self.checkButton.layer.cornerRadius = 5;
    self.checkButton.layer.masksToBounds = YES;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.shopName becomeFirstResponder];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - 字符串转码
- (NSString *)converStringWith:(NSString *)orignal {
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)orignal, NULL, NULL, kCFStringEncodingUTF8));
}

@end
